package com.easydict.config;

import com.easydict.core.ModuleConfigurationManager;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * EasyDict Jackson自动配置类
 * @author EasyDict
 * @version 1.0.1
 * @since 1.0.0
 */
@Configuration
@ConditionalOnClass({Module.class, SimpleModule.class})
@ConditionalOnProperty(prefix = "easydict", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(EasyDictProperties.class)
public class EasyDictJacksonConfig {

    private final EasyDictProperties properties;

    public EasyDictJacksonConfig(EasyDictProperties properties) {
        this.properties = properties;
    }


    /**
     * 创建模块配置管理器
     * <p>
     * 负责管理Jackson模块的配置和生命周期。
     * </p>
     *
     * @return 模块配置管理器实例
     */
    @Bean
    @ConditionalOnMissingBean(ModuleConfigurationManager.class)
    public ModuleConfigurationManager moduleConfigurationManager() {
        return new ModuleConfigurationManager(properties);
    }

    /**
     * 创建EasyDict Jackson模块
     * <p>
     * 核心的Jackson模块，负责在JSON序列化时自动添加字典字段。
     * 使用配置的字典后缀和字典提供者来实现字典转换功能。
     * </p>
     *
     * @param dictProvider 字典提供者
     * @param configManager 配置管理器
     * @return Jackson模块实例
     */
    @Bean
    public Module easyDictModule(DictProvider dictProvider,
                                ModuleConfigurationManager configManager) {

        SimpleModule module = new SimpleModule(
                configManager.getModuleName(),
                configManager.getModuleVersion()
        );

        // 使用增强的序列化修改器，传递配置的后缀
        DicTypeBeanSerializerModifier modifier = new DicTypeBeanSerializerModifier(
                dictProvider,
                properties.getDictSuffix()
        );
        module.setSerializerModifier(modifier);

        // 注册模块到配置管理器
        configManager.registerModule(module, modifier);

        return module;
    }
}
